﻿using LitJson;
using System.IO;
using System.Text;
using UnityEngine;

namespace BToolkit
{
    /// <summary>
    /// 与PlayerPrefs的区别是以文本文件存储，方便指定存储目录，方便编辑或移动（比如exe应用多需要存储在应用程序目录下而非系统沙箱中）
    /// 应用结束时自动保存,也可手动调用BPlayerPrefs.Save()提前保存
    /// </summary>
    public class BPlayerPrefs : MonoBehaviour
    {
        private const string FileName = "BPlayerPrefs";
        private static JsonData jsonData;
        private static BPlayerPrefs _BPlayerPrefs;

        private void OnDestroy()
        {
            //应用结束时自动保存
            Save();
        }

        private static void CheckReadJsonData()
        {
            if (jsonData == null)
            {
                string path = SavePath + "/" + FileName;
                if (File.Exists(path))
                {
                    string jsonStr = File.ReadAllText(path, Encoding.UTF8);
                    jsonData = JsonMapper.ToObject(jsonStr);
                }
            }
        }

        private static string SavePath
        {
            get
            {
                if (Application.isEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer)
                {
                    return Application.dataPath.Replace("/Assets", "") + "/Res";
                }
                else
                {
                    return Application.persistentDataPath;
                }
            }
        }

        private static void CheckCreateGameObject()
        {
            if (!_BPlayerPrefs)
            {
                _BPlayerPrefs = FindObjectOfType<BPlayerPrefs>();
                if (!_BPlayerPrefs)
                {
                    GameObject go = new GameObject("BPlayerPrefs");
                    DontDestroyOnLoad(go);
                    _BPlayerPrefs = go.AddComponent<BPlayerPrefs>();
                }
            }
        }

        public static void SetBool(string key, bool value)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData == null) jsonData = new JsonData();
            jsonData[key] = value;
        }

        public static void SetInt(string key, int value)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData == null) jsonData = new JsonData();
            jsonData[key] = value;
        }

        public static void SetFloat(string key, float value)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData == null) jsonData = new JsonData();
            jsonData[key] = value;
        }

        public static void SetString(string key, string value)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData == null) jsonData = new JsonData();
            jsonData[key] = value;
        }

        public static bool GetBool(string key, bool _default = false)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData != null && jsonData.ContainsKey(key))
            {
                return (bool)jsonData[key];
            }
            return _default;
        }

        public static int GetInt(string key, int _default = 0)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData != null && jsonData.ContainsKey(key))
            {
                return (int)jsonData[key];
            }
            return _default;
        }

        public static float GetFloat(string key, float _default = 0f)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData != null && jsonData.ContainsKey(key))
            {
                return (float)jsonData[key];
            }
            return _default;
        }

        public static string GetString(string key, string _default = null)
        {
            CheckCreateGameObject();
            CheckReadJsonData();
            if (jsonData != null && jsonData.ContainsKey(key))
            {
                return (string)jsonData[key];
            }
            return _default;
        }

        public static void Save()
        {
            if (jsonData != null)
            {
                string path = SavePath + "/" + FileName;
                string jsonStr = JsonMapper.ToJson(jsonData);
                Debug.Log("已保存到：" + path);
                File.WriteAllText(path, jsonStr, Encoding.UTF8);
            }
        }
    }
}